import { postJson, post } from '@/util/http'
import { readUkey, signData } from './ukey'
/**
 * ukey签章
 */
class UkeySeal {
  constructor(baseurl, id) {
    this.baseurl = baseurl || process.env.VUE_APP_SEAL_BASE_PATH
    this.id = id
  }
  async seal(seals, paging) {
    // 读证书
    let cert = readUkey()
    console.log('test-ukeyseal:3->')
    // 开始签章
    return postJson(`${this.baseurl}/pdf/startSeal`, {
      id: this.id,
      cert: cert,
      sealStr: '', // 签章图片，签章服务自行获取
      seals: seals,
      paging: paging
    }).then(async res => {
      console.log('test-ukeyseal:3->', res)
      if (res.status !== 0) {
        return Promise.reject(new Error(res.msg || '签章异常'))
      }
      // 签章
      return this.finishOne(res.data)
    }).catch(err => {
      console.log('test-ukeyseal:4->', err)
      return Promise.reject(new Error(`pdf签署失败`))
    })
  }
  /**
     * 完成单个签章
     */
  async finishOne(data) {
    // 签名处理
    if (data.complete) {
      // 结束
      console.log('test-ukeyseal:5->', '完成')
      return Promise.resolve('签署成功')
    }
    // 继续
    return this.signSeal(data.index, signData(data.digest, true))
  }
  /**
     * pdf摘要签名
     * @param {*} index
     * @param {*} data
     */
  async signSeal(index, data) {
    let result = await this.loadRemoteData(`${this.baseurl}/pdf/sign`, {
      id: this.id,
      index: index,
      base64SignedDate: data
    })
    if (!result) {
      console.log('test-ukeyseal:6->', '签章失败')
      return Promise.reject(new Error('签章失败'))
    }
    // 签章
    return this.finishOne(result)
  }
  loadRemoteData(url, params) {
    return post(url, params).then(res => {
      if (res.status === 0) {
        return res.data
      } else {
        return false
      }
    }).catch(err => {
      console.log(err)
      return false
    })
  }
}

export default UkeySeal
